const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');

// 创建上传目录
const uploadsDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
}

// 配置multer存储
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, uploadsDir);
    },
    filename: (req, file, cb) => {
        try {
            // 安全的文件名处理
            let originalName = file.originalname;
            
            // 尝试不同的编码方式
            try {
                // 如果是乱码，尝试从latin1转utf8
                if (originalName.includes('�') || /[\x80-\xFF]/.test(originalName)) {
                    originalName = Buffer.from(originalName, 'latin1').toString('utf8');
                }
            } catch (e) {
                console.log('编码转换失败，使用原始文件名');
            }
            
            // 清理文件名，移除不安全的字符
            const cleanName = originalName
                .replace(/[<>:"/\\|?*]/g, '_')  // 替换Windows不支持的字符
                .replace(/[\x00-\x1f\x80-\x9f]/g, '_')  // 替换控制字符
                .replace(/^\.|\.$/, '_')  // 处理以点开头或结尾的文件名
                .substring(0, 100);  // 限制文件名长度
            
            // 确保文件扩展名正确
            const ext = path.extname(cleanName) || '.xlsx';
            const nameWithoutExt = path.basename(cleanName, ext);
            
            const uniqueName = `${Date.now()}-${uuidv4()}-${nameWithoutExt}${ext}`;
            
            cb(null, uniqueName);
        } catch (error) {
            console.error('文件名处理错误:', error);
            // 如果处理失败，使用安全的默认名称
            const ext = '.xlsx';
            const safeName = `${Date.now()}-${uuidv4()}${ext}`;
            cb(null, safeName);
        }
    }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
    try {
        // 安全的文件名编码处理
        let originalName = file.originalname;
        
        // 尝试编码转换
        try {
            if (originalName.includes('�') || /[\x80-\xFF]/.test(originalName)) {
                originalName = Buffer.from(originalName, 'latin1').toString('utf8');
            }
        } catch (e) {
            console.log('fileFilter编码转换失败');
        }
        
        // 更新文件对象的原始名称
        file.originalname = originalName;
        
        const allowedTypes = ['.xlsx', '.xls', '.csv'];
        const ext = path.extname(originalName).toLowerCase();
        
        if (allowedTypes.includes(ext)) {
            cb(null, true);
        } else {
            cb(new Error('只支持Excel和CSV文件'));
        }
    } catch (error) {
        console.error('fileFilter错误:', error);
        cb(new Error('文件处理失败'));
    }
};

const upload = multer({ 
    storage: storage,
    fileFilter: fileFilter,
    limits: {
        fileSize: 50 * 1024 * 1024 // 50MB限制
    }
});

module.exports = { upload, uploadsDir };